package com.news.controller;

import com.news.config.Constant;
import com.news.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by vitoling on 15/8/19.
 */

@Controller
public class UserController {

    @Resource
    private UserService userService;

    @RequestMapping("/user/login")
    public String login(@RequestParam(required = false) String username,
                        @RequestParam(required = false) String password,
                        HttpServletRequest request, HttpServletResponse response) {

//        boolean result = userService.checkUserLogin(username,password);
        boolean result = username.equals(Constant.DEFAULT_USERNAME) && password.equals(Constant.DEFAULT_PASSWORD);
        if (result) {
            //创建cookie对象
            Cookie usernameCookie = new Cookie(Constant.Login_User_Cookie_Username_Name, username);
            Cookie loginStatusCookie = new Cookie(Constant.Login_User_Cookie_Status_Name, String.valueOf(Constant.USER_LOGIN_STATUS_ACTIVE));
            //设置cookie为 60 * 30 s
            usernameCookie.setMaxAge(60 * 30);
            loginStatusCookie.setMaxAge(60 * 30);
            usernameCookie.setPath("/");
            loginStatusCookie.setPath("/");
            //添加cookie，让其生效
            response.addCookie(usernameCookie);
            response.addCookie(loginStatusCookie);
            return "redirect:/";
        }

        return "redirect:/gotoLogin";

    }

}
